import { BacktestEngine, AccountType } from './backtest-engine.service';
import { MarketDataService, KlineBar } from '../services/market-data.service';
import { utc8StringToDate } from '../utils/time.utils';
import { MomentumTrackingStrategy } from './strategies/momentum-tracking.strategy';
import { prepareData } from './data-provider';
import { getKlineBarMilliseconds } from './time-utils';

// --- 主运行函数 ---
async function main() {
  // 1. 配置参数
  const config = {
    symbol: 'ETH-USDT-SWAP',
    timeframe: KlineBar.MINUTE_15,
    startDateStr: '2025-06-01 00:00:00',
    endDateStr: '2025-07-23 23:59:59',
    initialBalance: 1000,
    feeRate: 0.0005,
    accountType: AccountType.CONTRACT, // 或 AccountType.SPOT
    leverage: 10,
  };

  // 2. 初始化服务
  const marketDataService = new MarketDataService();
  const startDate = utc8StringToDate(config.startDateStr);
  const endDate = utc8StringToDate(config.endDateStr);

  // 3. 实例化策略
  const strategy = new MomentumTrackingStrategy({
    accountType: config.accountType,
    leverage: config.leverage,
    fastEmaPeriod: 9,
    slowEmaPeriod: 50,
    rsiPeriod: 14,
    rsiUpperThreshold: 60,
    rsiLowerThreshold: 40,
    volumeMaPeriod: 5,
    volumeThreshold: 1.2,
    atrPeriod: 14,
    atrThreshold: 0.008,
    longStopLossRate: 0.008,  // 多头止损
    shortStopLossRate: 0.012, // 空头止损
    takeProfitRate: 0.2,     // 止盈
  });

  // 4. 计算预热期
  const timeframeMillis = getKlineBarMilliseconds(config.timeframe);
  const warmupStartDate = new Date(startDate.getTime() - strategy.warmupPeriod * timeframeMillis);

  // 5. 获取历史数据
  const fullHistoricalData = await prepareData(
    marketDataService,
    config.symbol,
    config.timeframe,
    warmupStartDate,
    endDate
  );
  if (fullHistoricalData.length === 0) {
    console.error("No historical data found for the given period.");
    return;
  }

  // 6. 初始化策略指标
  await strategy.initialize(fullHistoricalData);

  // 7. 筛选正式回测区间
  const backtestData = fullHistoricalData.filter(k => k.timestamp >= startDate.getTime());

  // 8. 创建并运行回测引擎
  const engine = new BacktestEngine(
    strategy,
    backtestData,
    {
      initialBalance: config.initialBalance,
      feeRate: config.feeRate,
      accountType: config.accountType,
      leverage: config.accountType === AccountType.CONTRACT ? config.leverage : undefined,
    }
  );
  engine.run();
}

main().catch(console.error);
